"use client"
import React, {useEffect, useRef, useState} from 'react'
// @ts-ignore
import {LuckyWheel} from '@lucky-canvas/react'
import {queryRaffleAwardList, randomRaffle} from '@/apis'
import {RaffleAwardVO} from "@/types/RaffleAwardVO";

export function LuckyWheelPage() {
    const [strategyId, setStrategyId] = useState<number | null>(null)
    const [prizes, setPrizes] = useState([])
    const myLucky = useRef<any>(null)

    const [blocks] = useState([
        {padding: '10px', background: '#869cfa', imgs: [{src: "https://bugstack.cn/images/system/blog-03.png"}]}
    ])

    const [buttons] = useState([
        {radius: '40%', background: '#617df2'},
        {radius: '35%', background: '#afc8ff'},
        {
            radius: '30%', background: '#869cfa',
            pointer: true,
            fonts: [{text: '开始', top: '-10px'}]
        }
    ])

    const queryRaffleAwardListHandle = async (strategyId: number) => {
        const {code, info, data} = await queryRaffleAwardList(strategyId);
        if (code !== "0000") {
            window.alert("获取抽奖奖品列表失败 code:" + code + " info:" + info)
            return;
        }

        const newPrizes = data.map((award: RaffleAwardVO, index: number) => {
            const background = index % 2 === 0 ? '#e9e8fe' : '#b8c5f2';
            return {
                background: background,
                fonts: [{id: award.awardId, text: award.awardTitle, top: '15px'}]
            };
        });

        setPrizes(newPrizes)
    }

    const randomRaffleHandle = async () => {
        const {code, info, data} = await randomRaffle(strategyId!);
        if (code !== "0000") {
            window.alert("获取抽奖结果失败 code:" + code + " info:" + info)
            return;
        }
        
        // 如果存在 awardIndex，返回 awardIndex - 1；否则根据 awardId 查找索引
        if (data.awardIndex !== undefined && data.awardIndex !== null) {
            return data.awardIndex - 1;
        } else {
            return prizes.findIndex(p =>
                //@ts-ignore
                p.fonts?.some(font => font.id === data.awardId)
            );
        }
    }

    useEffect(() => {
        if (typeof window !== 'undefined') {
            const queryParams = new URLSearchParams(window.location.search);
            const id = Number(queryParams.get('strategyId') ?? '0');
            setStrategyId(id)
            queryRaffleAwardListHandle(id)
        }
    }, [])

    return <div>
        <LuckyWheel
            ref={myLucky}
            width="300px"
            height="300px"
            blocks={blocks}
            prizes={prizes}
            buttons={buttons}
            onStart={() => {
                // @ts-ignore
                myLucky.current.play()
                setTimeout(() => {
                    randomRaffleHandle().then(prizeIndex => {
                        // @ts-ignore
                        myLucky.current.stop(prizeIndex)
                    });
                }, 2500)
            }}
            onEnd={
                // @ts-ignore
                prize => {
                    alert('恭喜你抽到【' + prize.fonts[0].text + '】奖品ID【' + prize.fonts[0].id + '】')
                }
            }
        />
    </div>
}
